<?php

namespace V6;

use Biz\Invoice\Invoice;

class  C_Invoice extends \ResourceClass
{
    public $isActive = true;
    public $remark = '获取发票详情、更改发票状态、新增发票接口';

    /**
     * 获取发票详情
     * @param array $req
     * @param array $post
     * @param $result
     * @return string
     */
    public function get(array $req, array $post, &$result)
    {
        try {
            /* 授权验证【开始】 */
            if (!isset($req['uid'])) {
                return 'require user id ';
            }
            if (!isset($req['userType'])) {
                return 'require user type';
            }
            if (!isset($req['k']) || !isset($req['t'])) {
                return 'data error';
            }
            if (!array_key_exists('id', $req) || empty($req['id'])) {
                return 'require resource id';
            }

            $user_cls = \Biz\UserHandler::getById($req['userType'], $req['uid']);
            if (!is_object($user_cls) || $user_cls->getEnterpriseId() == false) {
                return 'data error';
            }
            $enterprise_id = $user_cls->getEnterpriseId();

            /* 授权验证*/
            if (\Biz\UserHandler::checkAuth($req['userType'], $req['uid'], $enterprise_id, $req['id'] . $req['t'], $req['k']) == false) {
                return 'data illegal';
            }
            $invoice_id = $req['id'];
            $invoice_handler = new \Biz\InvoiceHandler();
            $invoice_cls = $invoice_handler->getInvoiceByIdAndEnterpriseId($invoice_id, $enterprise_id);
            if (!is_object($invoice_cls)) {
                return 'data empty';
            }
            $base_data = array(
                array(
                    'label' => '开具类型',
                    'value' => $invoice_cls->getReceiptTypeByType($invoice_cls->getReceiptType()),
                ),
                array(
                    'label' => '发票金额',
                    'value' => $invoice_cls->getPrice(),
                ),
                array(
                    'label' => '发票类型',
                    'value' => $invoice_cls->getInvoiceTypeByType($invoice_cls->getInvoiceType()),
                ),
            ); // 默认个人
            $append_data = array();
            if ($invoice_cls->getReceiptType() == \Cls\Invoice\Invoice::RECEIPT_TYPE_ENTERPRISE // 企业类型
                && $invoice_cls->getInvoiceType() == \Cls\Invoice\Invoice::INVOICE_TYPE_NORMAL // 增值税普通发票
            ) {

                // 发票抬头
                $append_data[] = array(
                    'label' => '发票抬头',
                    'value' => $invoice_cls->getTitle()
                );

            } else if ($invoice_cls->getReceiptType() == \Cls\Invoice\Invoice::RECEIPT_TYPE_ENTERPRISE // 企业类型
                && $invoice_cls->getInvoiceType() == \Cls\Invoice\Invoice::INVOICE_TYPE_DEDICATED // 增值税专用发票
            ) {
                $append_data = array(
                    array(
                        'label' => '统一社会信用代码',
                        'value' => $invoice_cls->getSocialCreditCode()
                    ),
                    array(
                        'label' => '开户名称',
                        'value' => $invoice_cls->getAccountName()
                    ),
                    array(
                        'label' => '开户银行',
                        'value' => $invoice_cls->getDepositBank()
                    ),
                    array(
                        'label' => '银行账户',
                        'value' => $invoice_cls->getBankAccount()
                    ),
                    array(
                        'label' => '注册场所地址',
                        'value' => $invoice_cls->getCurrentAddress()
                    ),
                    array(
                        'label' => '注册固定电话',
                        'value' => $invoice_cls->getTelephone()
                    ),
                );
            }
            $express_data = array();
            if ($invoice_cls->getStatus() != \Cls\Invoice\Invoice::STATUS_CREATE) {
                $express_data = array(
                    array(
                        'label' => '快递方式',
                        'value' => $invoice_cls->getExpressName()
                    ),
                    array(
                        'label' => '快递单号',
                        'value' => $invoice_cls->getExpressNumber()
                    ),
                );
            }
            $foot_data[] = array(
                'label' => '开票时间',
                'value' => $invoice_cls->getCreateTime()
            );
            // 开票时间
            $result['head'][] = array(
                'label' => '申请编号',
                'value' => $invoice_cls->getApplyCode(),
            );
            $result['body'] = array_merge($base_data, $append_data, $express_data, $foot_data);
            if ($invoice_cls->getStatus() == \Cls\Invoice\Invoice::STATUS_DELIVERY) {
                $result['foot'][] = array('title' => "确认发票", "action" => "create");
            }

        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }

    /**
     * 插入发票信息
     * @param array $req
     * @param array $post
     * @param $result
     * @return string
     */
    public function post(array $req, array $post, &$result)
    {
        if (!isset($req['uid'])) {
            return 'require user uid';
        }
        if (!isset($req['userType'])) {
            return 'require user type';
        }
        if (!isset($req['k']) || !isset($req['t'])) {
            return 'data error';
        }
        $user_cls = \Biz\UserHandler::getById($req['userType'], $req['uid']);
        if (!is_object($user_cls)) {
            return 'data illegal';
        }
        $enterprise_id = $user_cls->getEnterpriseId();
        if (\Biz\UserHandler::checkAuth($req['userType'], $req['uid'], $enterprise_id, $req['t'] . $post['payload'], $req['k']) == false) {
            return 'data illegal';
        }
        $data = base64_decode($post['payload']);
        @parse_str($data, $data);
        $receipt_type_list = \Cls\Invoice\Invoice::getReceiptTypeList();
        $receipt_type_ids = array_keys($receipt_type_list);
        if (!isset($data['receipt_type']) || !in_array($data['receipt_type'], $receipt_type_ids)) {
            return '开具类型错误';
        }
        $receipt_type = $data['receipt_type'];
        $invoice_type_list = \Cls\Invoice\Invoice::getInvoiceTypeList();
        $invoice_type_ids = array_keys($invoice_type_list);
        if (!isset($data['invoice_type']) || !in_array($data['invoice_type'], $invoice_type_ids)) {
            return '发票类型错误';
        }
        $invoice_type = $data['invoice_type'];
        if (!isset($data['price'])) {

            return '发票金额不能为空';
        }

        $price = sprintf("%.2f", $data['price']);
        if ($price == 0) {
            return '发票金额格式错误或发票金额为0';
        }
        $price = $data['price'];
        $title = '';
        $social_credit_code = '';
        $account_name = '';
        $deposit_bank = '';
        $bank_account = '';
        $current_address = '';
        $telephone = '';
        // 验证数据完整性
        if ($receipt_type == \Cls\Invoice\Invoice::RECEIPT_TYPE_ENTERPRISE // 企业类型
            && $invoice_type == \Cls\Invoice\Invoice::INVOICE_TYPE_NORMAL // 增值税普通发票
        ) {
            if (!isset($data['title']) || empty($data['title'])) {
                return '发票抬头不能为空';
            }
            $title = $data['title'];
        } else if ($receipt_type == \Cls\Invoice\Invoice::RECEIPT_TYPE_ENTERPRISE // 企业类型
            && $invoice_type == \Cls\Invoice\Invoice::INVOICE_TYPE_DEDICATED // 增值税专用发票
        ) {
            if (!isset($data['title']) || empty($data['title'])) {
                return '发票抬头不能为空';
            }
            if (!isset($data['social_credit_code']) || empty($data['social_credit_code'])) {
                return '统一社会信用代码不能为空';
            }
            if (!isset($data['account_name']) || empty($data['account_name'])) {
                return '开户名称不能为空';
            }
            if (!isset($data['deposit_bank']) || empty($data['deposit_bank'])) {
                return '开户银行不能为空';
            }
            if (!isset($data['bank_account']) || empty($data['bank_account'])) {
                return '银行账户不能为空';
            }
            if (!isset($data['current_address']) || empty($data['current_address'])) {
                return '注册场所地址不能为空';
            }
            if (!isset($data['telephone']) || empty($data['telephone'])) {
                return '注册固定电话不能为空';
            }

            $title = $data['title'];
            $social_credit_code = $data['social_credit_code'];
            $account_name = $data['account_name'];
            $deposit_bank = $data['deposit_bank'];
            $bank_account = $data['bank_account'];
            $current_address = $data['current_address'];
            $telephone = $data['telephone'];
        }
        $invoice_cls = new \Cls\Invoice\Invoice();
        $invoice_cls->setEnterpriseId($enterprise_id);
        $invoice_cls->setEnterpriseCustomerId($req['uid']);
        $invoice_cls->setReceiptType($receipt_type);
        $invoice_cls->setInvoiceType($invoice_type);
        $invoice_cls->setTitle($title);
        $invoice_cls->setPrice($price);
        $invoice_cls->setSocialCreditCode($social_credit_code);
        $invoice_cls->setAccountName($account_name);
        $invoice_cls->setDepositBank($deposit_bank);
        $invoice_cls->setBankAccount($bank_account);
        $invoice_cls->setCurrentAddress($current_address);
        $invoice_cls->setTelephone($telephone);
        $invoice_cls->setStatus(\Cls\Invoice\Invoice::STATUS_CREATE);
        $invoice_handler = new \Biz\InvoiceHandler();
        $result = $invoice_handler->insert($invoice_cls);
        if (!$result) {
            return '插入失败';
        }
    }

    /**
     * 确认发票接口，更改发票状态
     * @param array $req
     * @param array $post
     * @param $result
     * @return string
     */
    public function put(array $req, array $post, &$result)
    {
        try {
            if (!array_key_exists('id', $req) || empty($req['id'])) {
                return 'require resource id';
            }
            if (!isset($req['uid'])) {
                return 'require user id ';
            }
            if (!isset($req['userType'])) {
                return 'require user type';
            }
            if (!isset($req['k']) || !isset($req['t'])) {
                return 'data error';
            }
            if (!array_key_exists('payload', $post)) {
                return 'require payload';
            }
            $user_cls = \Biz\UserHandler::getById($req['userType'], $req['uid']);
            if (!is_object($user_cls)) {
                return 'data illegal';
            }
            $enterprise_id = $user_cls->getEnterpriseId();
            if (\Biz\UserHandler::checkAuth($req['userType'], $req['uid'], $enterprise_id, $req['id'] . $req['t'] . $post['payload'], $req['k']) == false) {
                return 'data illegal';
            }
            $data = base64_decode($post['payload']);
            @parse_str($data, $data);
            if (!array_key_exists('status', $data)) {
                return '状态为空';
            }
            $invoice_handler = new \Biz\InvoiceHandler();
            $invoice_cls = $invoice_handler->getInvoiceByIdAndEnterpriseId($req['id'], $req['enterpriseId']);
            if (!is_object($invoice_cls)) {
                return '数据不存在';
            }
            $status = $data['status'];
            $status_list = \Cls\Invoice\Invoice::getStatusList();
            $status_ids = array_keys($status_list);
            if (!in_array($status, $status_ids)) {
                return '状态值错误';
            }
            $invoice_cls->setId($req['id']);
            $invoice_cls->setStatus($status);
            $result = $invoice_handler->update($invoice_cls);
        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }
}